package com.hmdp.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.BooleanUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hmdp.dto.Result;
import com.hmdp.dto.UserDTO;
import com.hmdp.entity.Blog;
import com.hmdp.entity.Follow;
import com.hmdp.entity.ScrollResult;
import com.hmdp.entity.User;
import com.hmdp.mapper.BlogMapper;
import com.hmdp.service.IBlogService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.service.IFollowService;
import com.hmdp.service.IUserService;
import com.hmdp.utils.SystemConstants;
import com.hmdp.utils.UserHolder;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
public class BlogServiceImpl extends ServiceImpl<BlogMapper, Blog> implements IBlogService {

    @Resource
    private IUserService userService;

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Resource
    private IFollowService followService;

    @Override
    public Result queryHotBlog(Integer current) {
        // 根据用户查询
        Page<Blog> page = query()
                .orderByDesc("liked")
                .page(new Page<>(current, SystemConstants.MAX_PAGE_SIZE));
        // 获取当前页数据
        List<Blog> records = page.getRecords();

        // 查询用户
        records.forEach(blog -> {
            this.isBlogLiked(blog);
            this.queryBlogUser(blog);
        });

        return Result.ok(records);
    }

    @Override
    public Result queryBlogById(int id) {
        Blog blog = getById(id);

        if (blog == null) {
            return Result.fail("博客不存在");
        }

        queryBlogUser(blog);
        isBlogLiked(blog);

        return Result.ok(blog);
    }

    private void isBlogLiked(Blog blog) {

        UserDTO user = UserHolder.getUser();
        if(user==null)
            return;

        Long userId = UserHolder.getUser().getId();
        Double score = stringRedisTemplate.opsForZSet().score("blog:liked:" + blog.getId(), userId.toString());
        blog.setIsLike(score!=null);
    }

    public void queryBlogUser(Blog blog) {
        Long userId = blog.getUserId();
        User user = userService.getById(userId);
        blog.setName(user.getNickName());
        blog.setIcon(user.getIcon());
    }


    @Override
    public Result likeBlog(Long id) {
        //1 获取登录用户
        Long userId = UserHolder.getUser().getId();

        //2 判断是否点赞
        Double score = stringRedisTemplate.opsForZSet().score("blog:liked:" + id, userId.toString());

        //3 如果未点赞，则可以点赞
        if (score==null){
            //3.1 如果未点赞，则可以点赞
            //3.2 点赞则数据库点赞+1
            boolean success = update().setSql("liked = liked+1").eq("id",id).update();
            //3.3 保存用户到redis的set集合
            //  zadd key value score(time)
            if(success)
                stringRedisTemplate.opsForZSet().add("blog:liked:" + id, userId.toString(), System.currentTimeMillis());

        }else {
            //4 已点赞
            //4.1 数据库点赞数-1
            boolean success = update().setSql("liked = liked-1").eq("id",id).update();
            //4.2 redis中set集合移除用户
            if(success)
                stringRedisTemplate.opsForZSet().remove("blog:liked:" + id, userId.toString());
        }
        return Result.ok();

    }

    @Override
    public Result queryBlogLikes(int id) {

        String key = "blog:liked:" + id;
        //1 查询top5的点赞用户
        Set<String> top5 = stringRedisTemplate.opsForZSet().range(key, 0, 4);
        if(top5==null || top5.isEmpty()){
            return Result.ok(Collections.emptyList());
        }

        //2 解析出用户id
        List<Long> ids = top5.stream().map(Long::valueOf).collect(Collectors.toList());

        //3 根据用户id 查询用户
        List<User> users = userService.listByIds(ids);

        List<UserDTO> userDTOS = users.stream().map(user -> BeanUtil.copyProperties(user, UserDTO.class))
                .collect(Collectors.toList());

        //4 返回用户信息
        return Result.ok(userDTOS);
    }

    @Override
    public Result saveBlog(Blog blog) {
        //1 获取登录用户
        Long userId = UserHolder.getUser().getId();
        blog.setUserId(userId);

        //2 保存博客
        boolean save = save(blog);

        if(!save){
            return Result.fail("博客保存失败");
        }

        //3 获取登录用户的粉丝列表
        //select * from tb_follow where follow_user_id = ?
        List<Follow> follows = followService.query().eq("follow_user_id", userId).list();

        for (Follow follow : follows) {
            //4.1 获取粉丝id
            Long subUserId = follow.getUserId();

            //4.2 推送至粉丝收件箱
            String key = "feed:"+subUserId;
            stringRedisTemplate.opsForZSet().add(key, blog.getId().toString(), System.currentTimeMillis());

        }

        return Result.ok(blog.getId());
    }

    /**
     * 这个很难整
     * @param time 时间戳（set中的score值，用来排序）
     * @param offset 偏移量（一页展示几条数据）
     * @return ScrollResult类对象
     */
    @Override
    public Result queryBlogOfFollow(Long time, Integer offset) {

        //1 获取用户
        Long userId = UserHolder.getUser().getId();

        //2 查询redis中的收件箱
        String key = "feed:" + userId;

        //ZrevRangeByScore key Max Min Limit offset count WithScores
        //参数为五个 Key Max Min offset count
        Set<ZSetOperations.TypedTuple<String>> tuples = stringRedisTemplate.opsForZSet()
                .reverseRangeByScoreWithScores(key, 0, time, offset, 3);

        if(tuples.isEmpty() || tuples ==null){
            return Result.ok();
        }


        //3 解析数据: blogId minTime offset
        List<Long> blogIds = new ArrayList<>(tuples.size());
        long minTime = 0;
        int offset_temp = 1;


        for (ZSetOperations.TypedTuple<String> tuple : tuples) {
            //3.1 获取Blog的id
            Long id = Long.valueOf(tuple.getValue());
            blogIds.add(id);
            //3.2 获取时间戳

            long temp = tuple.getScore().longValue();
            if(temp == minTime){
                offset_temp++;
            }else{
                minTime = temp;
                offset_temp=1;
            }
        }


        //4 根据id查询blog
        String idStr = StrUtil.join(",", blogIds);
        List<Blog> blogs = query().in("id",blogIds).last("order by field(id," + idStr + ")").list();


        //4.1 给每个博客设置 (1)是否点赞、(2)博客作者信息显示
        for (Blog blog : blogs) {
            queryBlogUser(blog);
            isBlogLiked(blog);
        }


        //5 封装返回blog的List
        ScrollResult r = new ScrollResult();
        r.setList(blogs);
        r.setOffset(offset);
        r.setMinTime(minTime);

        return Result.ok(r);
    }

}
